package org.znxs.znxsojsandbox.service;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.znxs.znxsojsandbox.docker.DockerJavaRun;
import org.znxs.znxsojsandbox.model.ExecuteCodeRequest;
import org.znxs.znxsojsandbox.model.ExecuteCodeResponse;
import org.znxs.znxsojsandbox.model.ExecuteMessage;
import org.znxs.znxsojsandbox.model.JudgeInfo;
import org.znxs.znxsojsandbox.utils.ProcessUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 具体实现
 */
@Service
@Slf4j
public class CodeSandboxImpl implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "src\\main\\resources\\sandbox\\testFiles";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";


    @Resource
    private DockerJavaRun dockerJavaRun;

    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        // 非空判断

        String userCodeParentPath = null;

        File userCodeFile = null;
        List<ExecuteMessage> executeMessageList = null;
        try {
            if (executeCodeRequest == null || StrUtil.isBlank(executeCodeRequest.getCode())) {
                throw new Exception("请求参数为空");
            }
            // 1) 获取代码，进行写入
            String code = executeCodeRequest.getCode();
            // 在具体的代码文件目录下面存储代码到Main文件内，并且创建不同的文件夹，
            String userDir = System.getProperty("user.dir");
            String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
            // 判断全局代码目录是否存在，没有则新建
            if (!FileUtil.exist(globalCodePathName)) {
                FileUtil.mkdir(globalCodePathName);
            }
            // 把用户的代码隔离存放
            UUID fileUUIDPath = UUID.randomUUID();
            userCodeParentPath = globalCodePathName + File.separator + fileUUIDPath;
            String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
            userCodeFile = FileUtil.writeString(code, userCodePath, "UTF-8");

            // 2) 通过执行命令，进行编译 并创建编译之后的.class文件
            String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
            Process process = Runtime.getRuntime().exec(compileCmd);
            // 等待编译完成
            int exitValue = process.waitFor();
            log.info("编译完成，退出码为：" + exitValue + "0-正常，1-通用错误或异常情况，2-用法错误，126-命令找到但无法执行，127-命令无法找到，255-表示严重的系统错误");

            // 3) 运行程序
            // 传统运行方式
//            runCodeTraditional(executeMessageList, executeCodeRequest, userCodeParentPath);
            // 通过docker 运行
            // 因为是在本地，处理一下路径问题
            String dockerMatchPath = userCodeFile.getParentFile().getParentFile().getAbsolutePath();
            log.info(dockerMatchPath);
            executeMessageList = dockerJavaRun.dockerRun(executeCodeRequest, userCodeFile);

        } catch (Exception e) {
            return getErrorResponse(e);
        }

        // 4) 整理输出
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        ArrayList<String> outputList = new ArrayList<>();
        // 获取最大时间 判断是否超时  获取最大内存占用
        long maxTime = 0;
        long maxMemory = 0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            // 判断是否有错误信息
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            // 没有错误，直接添加输出用例
            outputList.add(executeMessage.getMessage());
            // 统计最长时间
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
            // 统计最大内存占用
            Long memory = executeMessage.getMemory();
            if (memory != null) {
                maxMemory = Math.max(maxMemory, memory);
            }
        }

        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            // 表示运行成功
            executeCodeResponse.setStatus(1);
        }
        // 这里的message指的是整个程序执行信息
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setMemoryLimit(maxMemory);
        judgeInfo.setTime(maxTime);
        // 内存信息不容易获取，所以这里不做获取
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 5) 文件清除
//        if (userCodeFile.getParentFile() != null) {
//            boolean del = FileUtil.del(userCodeParentPath);
//            System.out.println("删除" + (del ? "成功" : "失败"));
//        }


        return executeCodeResponse;
    }


    /**
     * 6) 错误处理
     * 异常处理方法
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    /**
     * 传统运行方式
     */
    private void runCodeTraditional(ArrayList<ExecuteMessage> executeMessageList, ExecuteCodeRequest executeCodeRequest, String userCodeParentPath) throws IOException {        // 获取输入用例
        List<String> inputList = executeCodeRequest.getInputList();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            System.out.println(runCmd);
            Process runProcess = Runtime.getRuntime().exec(runCmd);
            // 执行代码，获取运行信息
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
            // 获取所有执行信息
            executeMessageList.add(executeMessage);
            System.out.println("控制台输出结果" + executeMessage.getMessage());
            System.out.println("退出值" + executeMessage.getExitValue());
            System.out.println("错误消息" + executeMessage.getErrorMessage());
        }
    }

}
